package com.example.goodsmanagementcabinet.base;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentTransaction;

import com.android.volley.error.VolleyError;
import com.example.goodsmanagementcabinet.R;
import com.example.goodsmanagementcabinet.activity.HomeActivity_;
import com.example.goodsmanagementcabinet.db.DatabaseManager;
import com.example.goodsmanagementcabinet.otto.OttoManager;
import com.example.goodsmanagementcabinet.otto.OttoMsg;
import com.example.goodsmanagementcabinet.speaker.Speaker_;
import com.example.goodsmanagementcabinet.utils.Utils;
import com.orhanobut.logger.Logger;

import org.androidannotations.annotations.UiThread;

import java.util.ArrayList;
import java.util.List;

import static java.lang.Thread.sleep;

public abstract class BaseActivity extends AppCompatActivity {
    public static List<Activity> sActivityList = new ArrayList<Activity>();
    public String TAG;
    public static long onTouchEventTime = 0;
    boolean isRuning = true;
    public Dialog acapterDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        TAG = getClass().getName();
        sActivityList.add(this);
        OttoManager.getInstance().onSubscribe(this);
        System.out.println("----> otto 注册成功");
        hideBottomUIMenu();
        onTouchEventTime = System.currentTimeMillis();
        if (!Utils.isTopActivity("HomeActivity_")) {
            afterTimeToHome();
        }
    }

    public FragmentTransaction beginTransaction() {
        return getSupportFragmentManager().beginTransaction();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        hideBottomUIMenu();
    }

    public void afterTimeToHome() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (isRuning) {
                    if (System.currentTimeMillis() - onTouchEventTime > 1000 * 60 * 4) {
                        isRuning = false;
                        toHome();
                    }
                    try {
                        sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        sActivityList.remove(this);
        isRuning = false;
        acapterDialog = null;
        OttoManager.getInstance().offSubscribe(this);
    }

    protected void hideBottomUIMenu() {
        // 隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) {
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

    public static void hideAllInputMethod(Activity act) {
        // 从系统服务中获取输入法管理器
        InputMethodManager imm = (InputMethodManager) act.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) { // 软键盘如果已经打开则关闭之
            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }


    /**
     * 退出程序
     */
    public static void finishActivitys() {
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    /**
     * debug 日志
     *
     * @param msg
     */
    public void d(String msg) {
        Logger.d(msg);
    }

    /**
     * 错误日志
     *
     * @param msg
     */
    public void e(String msg) {
        Logger.e(msg);
    }

    /**
     * Toast
     *
     * @param msg
     */
    public void t(String msg) {
        boolean isMainThread = Thread.currentThread() == Looper.getMainLooper().getThread();
        if (!isMainThread) {
            Looper.prepare();
            Toast.makeText(GoodBoxManagerApp_.getInstance(), msg, Toast.LENGTH_SHORT).show();
            Logger.d(msg);
        } else {
            Toast.makeText(GoodBoxManagerApp_.getInstance(), msg, Toast.LENGTH_SHORT).show();
            Logger.d(msg);
        }
    }


    public void close(View v) {
        this.finish();
    }

    public void toHome(View v) {
        Intent i = new Intent(this, HomeActivity_.class);
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(i);

    }

    public void toHome() {
        Log.e("无操作时间超过限定时间-----", "自动返回首页----");
        Intent i = new Intent(this, HomeActivity_.class);
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(i);

    }

    public void acapterDialog() {
        if (acapterDialog == null) {
            acapterDialog = new Dialog(this, R.style.add_dialog);
            acapterDialog.setContentView(R.layout.item_pop_delete);
            acapterDialog.setCancelable(false);
            WindowManager.LayoutParams layoutParams = acapterDialog.getWindow().getAttributes();
            acapterDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
            acapterDialog.getWindow().setAttributes(layoutParams);
            Window dialogWindow = acapterDialog.getWindow();
            dialogWindow.setGravity(Gravity.CENTER_HORIZONTAL);
            TextView textView = acapterDialog.findViewById(R.id.tv_user);
            textView.setText("");
            Button affirmBtn = acapterDialog.findViewById(R.id.accptBtn);
            final Button mCancleBtn = acapterDialog.findViewById(R.id.cancelBtn);
            //textView = dialog.findViewById(R.id.)
            affirmBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    toHome();
                    OttoManager.getInstance().deliverMsg(OttoMsg.OTTO_IS_TO_HOME,null);
                    acapterDialog.dismiss();
                }
            });

            mCancleBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    acapterDialog.dismiss();
                }
            });
        }
        TextView textView = acapterDialog.findViewById(R.id.tv_user);
        textView.setText("");
        acapterDialog.show();
    }

    public void speak(String s) {
        Speaker_.getInstance_(GoodBoxManagerApp_.getInstance()).speak(s);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        onTouchEventTime = System.currentTimeMillis();
        return false;
    }

    public boolean isArray(String json) {
        if (TextUtils.isEmpty(json)) {
            return false;
        } else {
            return json.indexOf("[") >= 0;
        }
    }
}
